<?php 

Class indexController extends appController
{
	
    /**
     * 首页
     */
	public function index()
	{
	    $this->checkUser(2);
	    $index = Model('index');
	    
	    $type = $_GET['type'];
	    $this->assign("type", $type);
	    
	    $giftConfig = $index->getGameConfig();//获取配置信息
	    $this->assign('config', $giftConfig);
	    
	    $userJoinInfo = $index->getUserJoinInfo(session('wxid'), session('openid'));//获取参与记录
	    $canplay = $this->playStatus($giftConfig, $userJoinInfo);//判断是否能继续游戏
	    session('canplayStatus', $canplay['status']);
	    session('canplayType', $canplay['type']);
	    $this->assign('canplay', $canplay);

	    session('id', $userJoinInfo['id']);
	    session('sign', $this->setSign(array('wxid' => session('wxid'), 'openid' => session('openid'), 'recode' => $userJoinInfo['id'])));  
	    
	    $shareInfo = $this->getShareInfo('index');//获取分享信息
	    $this->assign('shareInfo', json_encode($shareInfo));
	    
	    if($_GET['id'])
	    {
	        session('tempId', $_GET['id']);
	        session('tempSign', $_GET['sign']);
	    }
	    
	    $jsdk = $index->get_jsdk_api('wxea3c4cf35fa4db74', 'stamp');
	    $this->assign('jsdk', json_encode($jsdk));
	    $score = $this->getScore(30);//获取排名信息
	    $this->assign('score', $score);
	    
		$this->assign_global();
		$this->display("index.html");
	}
	
	/**
	 * 游戏页
	 */
	public function game()
	{
	    $index = Model('index');
	    $id = session('tempId');
	    $sign = session('tempSign');
	    session('tempId', null);
	    session('tempSign', null);
	    if(!session('wxid') || !session('openid'))
	    {
	        header('Location:http://'.$_SERVER['HTTP_HOST'].'/'.DIR.'index.php?g=mobile&m=index&a=index&id='.$id.'&sign='.$sign);
	        exit;
	    }
	    if(session('canplayStatus'))
	    {
	        $this->assign('playType', session('canplayType'));
	        session('canplayType', null);
	        session('canplayStatus', null);
	        
	        $shareUser = $index->getShareUserJoin($id);
	        $tempSign = $this->setSign(array('wxid' => $shareUser['wxid'], 'openid' => $shareUser['openid'], 'recode' => $shareUser['id']));
	        if($tempSign != $sign)
	        {
	            $shareWxid = 0;
	            $shareOpenid = 0;
	        }
	        else 
	        {
	            if($tempSign != session('sign'))
	            {
	                $shareWxid = $shareUser['wxid'];
	                $shareOpenid = $shareUser['openid'];
	            }
	            else 
	            {
	                $shareWxid = 0;
	                $shareOpenid = 0;
	            }
	        }
	        $this->assign('shareWxid', $shareWxid);
	        $this->assign('shareOpenid', $shareOpenid);
	        $this->assign('wxid', session('wxid'));
	        $this->assign('openid', session('openid'));
	        $this->assign('sign', session('sign'));
	        $this->assign('id', session('id'));
	        
	        $this->assign_global();
	        $this->display('game.html');
	    }
	    else
	    {
	        header('Location:http://'.$_SERVER['HTTP_HOST'].'/'.DIR.'index.php?g=mobile&m=index&a=index&id='.$id.'&sign='.$sign);
	        exit;
	    }
	}
	
	/**
	 * 调用授权接口1:正常授权 , 2:集邮接口授权
	 * @param number $api
	 * @param string $type
	 */
	public function checkUser($api = 1, $type = 'index')
	{
	    switch($api)
	    {
	        case 1:
	            $this->getUserOpenid();
	            break;
	        case 2:
	            $this->checkUserApi($type);
	            break;
	        default:
	            $this->getUserOpenid();
	            break;
	    }
	}
	
	/**
	 * 集邮的接口授权
	 */
	public function checkUserApi($type = 'index')
	{
	    if(!session('wxid') || !session('openid'))
	    {
	        session('tempId', $_GET['id']);
	        session('tempSign', $_GET['sign']);
	        $url = "http://".$_SERVER['HTTP_HOST']."/".DIR."index.php?g=mobile&m=index&a=getUser&type=".$type;
	        header("Location:http://dcj.szhkhui.com/api/api_author.php?user=szjy_lly360&scope=snsapi_userinfo&redirect_uri=".urlencode($url));
	        exit;
	    }
	}
	
	/**
	 * 集邮接口获取并存储用户信息
	 */
	public function getUser()
	{
	    $index = Model('index');
	    if($_POST)
	    {
	        $res = array('error' => 1, 'content' => '获取用户失败');
	        $openid = $info['openid'] = $_POST['openid'];
	        $info['nickname'] = $_POST['nickname'];
	        $info['sex'] = $_POST['sex'];
	        $info['headimgurl'] = $_POST['headimgurl'];
	        $info['province'] = $_POST['province'];
	        $info['city'] = $_POST['city'];
	        $info['country'] = $_POST['country'];
	        $type = $_GET['type'];
	        	
	        $isExistUser = $index->checkExistInfo($info['openid']);//确认是否已经存在用户信息
	        if($isExistUser)
	        {
	            unset($info['openid']);
	            $update = $index->updateUser($info, $openid);//更新用户信息
	            if($update)
	            {
	                $wxuser = $index->getUserInfo(array('id', 'openid'), array('openid' => $openid));//获取用户信息，id，openid
	            }
	            else
	            {
	                echo "系统错误";
	                exit;
	            }
	        }
	        else
	        {
	            $wxid = $index->insertUser($info);//插入用户信息
	            if($wxid)
	            {
	                $wxuser = $index->getUserInfo(array('id', 'openid'), array('openid' => $openid));//获取用户信息，id，openid
	            }
	            else
	            {
	                echo "系统错误";
	                exit;
	            }
	        }
	        
	        session('nickname', $wxuser['nickname']);
	        session('wxid', $wxuser['id']);
	        session('openid', $wxuser['openid']);
	        
	        $id = session('tempId');
	        $sign = session('tempSign');
	        session('tempId', null);
	        session('tempSign', null);
            header("Location:http://".$_SERVER['HTTP_HOST']."/".DIR."index.php?g=mobile&m=index&a=".$type."&id=".$id."&sign=".$sign);
            exit;
	        
	    }
	}
	
    /**
	 * 普通获取授权
	 */
	public function getUserOpenid()
	{
	    $index = Model('index');
	    $wx = new weixinController();
	    $config = $index->weixin_config();
	    if(!session('wxid') && !session('openid'))
	    {
	        if(!isset($_GET['code']))
	        {
	            $url = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'].'&type=user_base';
                $wx->getUserUrl($config['appid'], $url, false);
	        }
	        else 
	        {
	            $type = $_GET['type'];
	            $code = $_GET['code'];
	            $arr = $wx->getUserByCode($config['appid'], $config['appsecret'], $code);
	            $isExistOpenid = $index->checkExistInfo($arr['openid']);
	            if($isExistOpenid)
	            {
	                $userInfo = $index->getUserInfo('*', array('openid' => $arr['openid']));
                    if($userInfo['access_time'] < yf_time() && $type == 'user_base')
                    {
                        $url = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
    	                $urlTemp = explode("&code", $url);
    	                $url = $urlTemp['0'].'&type=user_info';
    	                $wx->getUserUrl($config['appid'], $url);
                    }
                    else 
                    {
                        if($type == 'user_info')
                        {
                            $str = $wx->getUserInfo($arr['openid'], $arr['access_token']);
                            $openid = $str['openid'];
                            $userInfo['nickname'] = $info['nickname'] = $str['nickname'];
                            $info['sex'] = $str['sex'];
                            $info['headimgurl'] = $str['headimgurl'];
                            $info['country'] = $str['country'];
                            $info['city'] = $str['city'];
                            $info['province'] = $str['province'];
                            $info['access_time'] = yf_time() + $arr['expires_in'] - 200;
                            $id = $index->updateUser($info, $openid);
                            if(!$id)
                            {
                                
                            }
                        }
                    }
                    $nickname = $userInfo['nickname'];
                    $wxid = $userInfo['id'];
                    $openid = $userInfo['openid'];
	            }
	            else
	            {
	                if($type == 'user_base')
	                {
    	                $url = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
    	                $urlTemp = explode("&code", $url);
    	                $url = $urlTemp['0'].'&type=user_info';
    	                $wx->getUserUrl($config['appid'], $url);
	                }
	                if($type == 'user_info') 
	                {
    	                $str = $wx->getUserInfo($arr['openid'], $arr['access_token']);
    					$info['openid'] = $str['openid'];
    					$nickname = $info['nickname'] = $str['nickname'];
    					$info['sex'] = $str['sex'];
    					$info['headimgurl'] = $str['headimgurl'];
    					$info['country'] = $str['country'];
    					$info['city'] = $str['city'];
    					$info['province'] = $str['province'];
    					$info['access_time'] = yf_time() + $arr['expires_in'] - 200;
    					$wxid = $index->insertUser($info);
    					if(!$wxid)
    					{
    					    echo "System Error!";
    					    exit;
    					}
    					$openid = $arr['openid'];
	                }
	            }
				session('wxid', $wxid);
				session('openid', $openid);
				session('nickname', $nickname);
	        }
	    }
	}
	
	/**
	 * 玩游戏的状态
	 * @param unknown $wxid
	 * @param unknown $openid
	 * @param unknown $recode
	 */
	public function playStatus($config, $recode)
	{
	    $index = Model('index');
	    $canplay = array(
	        'status' => 0,
	        'type' => 'gameCount',
	        'msg' => '您今天的游戏次数已用完!成功分享好友1次，参与机会+3。'
	    );
	    
	    if($config['limit_status'])//判断是否开启了限制模式
	    {
	        $user_count = $index->getLimitRecode($recode['wxid'], $recode['openid'], $config['limit_time']);
	        if($user_count >= $config['limit_count'])//符合限制的条件
	        {
	            $canplay = array(
	                'status' => 0,
	                'type' => 'gameCount',
	                'msg' => '当前时间内游戏次数超过限制,请一段时间后再玩'
	            );
	            return $canplay;
	        }
	    }
	    
	    if($config['count_type'] == 1)//游戏的类型,每天
	    {
	        $nowDate = date('Y-m-d', yf_time());
	        $oldDate = date('Y-m-d', $recode['created']);
	        if($nowDate == $oldDate)//判断当前游戏记录是否是最新的
	        {
                if($recode['gameCount'] < $config['game_count'])//游戏次数未超过设定值
                {
                    $canplay = array(
                        'status' => 1,
                        'type' => 'gameCount',
                        'msg' => ''
                    );
                    return $canplay;
                }	            
	        }
	        else 
	        {
	            $index->updateJoinRecodeStart($recode['id']);//更新当前记录的次数和时间
	            $recode['gameCount'] = 0;
	            $recode['created'] = yf_time();
	            $canplay = array(
	                'status' => 1,
	                'type' => 'gameCount',
	                'msg' => ''
	            );
	            return $canplay;
	        }
	    }
	    elseif($config['count_type'] == 2)//游戏类型,一共
	    {
	        if($recode['gameCount'] < $config['game_count'])//游戏次数未超过设定次数
	        {
	            $canplay = array(
	                'status' => 1,
	                'type' => 'gameCount',
	                'msg' => ''
	            );
	            return $canplay;
	        }
	    }
	    else//游戏次数不限制
	    {
	        $canplay = array(
	            'status' => 1,
	            'type' => 'gameCount',
	            'msg' => ''
	        );
	        return $canplay;
	    }
	    
	    if($config['is_share'])//是否开启了分享模式
	    {
	        if($recode['shareCount'] < $recode['gameShare'])//判断分享的游戏次数是否足够游戏
	        {
	            $canplay = array(
	                'status' => 1,
	                'type' => 'shareCount',
	                'msg' => ''
	            );
	            return $canplay;
	        }
	    }
	    return $canplay;
	}
	
	/**
	 * 获取分享的信息
	 */
	public function getShareInfo($code = 'index')
	{
	    $index = Model('index');
	    $shareInfo = $index->getShareInfo($code);
	    if($shareInfo)
	    {
	        if(strpos($shareInfo['share_url'], '{{url}}'))
	        {
	            $dir = str_replace('/', '', DIR);
	            $shareInfo['share_url'] = str_replace('{{url}}', $_SERVER['HTTP_HOST'].'/'.$dir, $shareInfo['share_url']);
	        }
	        if(strpos($shareInfo['share_url'], '{{user}}'))
	        {
	            $shareInfo['share_url'] = str_replace('{{user}}', session('wxid'), $shareInfo['share_url']);
	        }
	        if(strpos($shareInfo['share_url'], '{{sign}}'))
	        {
	            $shareInfo['share_url'] = str_replace('{{sign}}', session('sign'), $shareInfo['share_url']);
	        }
	        $shareInfo['share_logo'] = 'http://'.$_SERVER['HTTP_HOST'].'/'.$dir.$shareInfo['share_logo'];
	    }
	    return $shareInfo;
	}
	
	/**
	 * 获取排名
	 * @param number $limit 获取数量
	 * @param string $type 是否获取当前用户排名
	 * @return Ambigous <multitype:, multitype:multitype:number  unknown , multitype:unknown >
	 */
	public function getScore($limit = 10, $type = false)
	{
	    $arr = array();
	    $index = Model('index');
	    $num = 1;
	    if($type)
	    {
	        $score = $index->getScoreInfo();
	        $scoreTemp = array();
	        $myInfo = array(
	            'status' => 0,
	            'msg' => '排名外'
	        );
	        if($score)
	        {
    	        foreach($score as $k => $v)
    	        {
    	            if($num <= $limit)
    	            {
    	                $scoreTemp[$k] = $v;
    	                $scoreTemp[$k]['num'] = $num;
    	                $userInfo = $index->getUserInfo('nickname, headimgurl', array('id' => $v['wxid'], 'openid' => $v['openid']));
    	                $scoreTemp[$k]['nickname'] = $userInfo['nickname'];
    	                $scoreTemp[$k]['headimgurl'] = $userInfo['headimgurl'];
    	            }
    	            if(session('wxid') == $v['wxid'] && session('openid') == $v['openid'])
    	            {
    	                $myInfo = array(
    	                    'status' => 1,
    	                    'msg' => $num
    	                );
    	                if($num > $limit)
    	                {
    	                    break;
    	                }
    	            }
    	            $num++;
    	        }
	        }
	        $arr = array(
	            'data' => $scoreTemp,
	            'myScore' => $myInfo
	        );
	    }
	    else
	    {
	        $score = $index->getScoreInfo($limit);
	        if($score)
	        {
	            $num = 1;
	            foreach($score as $k => $v)
	            {
	                $userInfo = $index->getUserInfo('nickname, headimgurl', array('id' => $v['wxid'], 'openid' => $v['openid']));
	                $score[$k]['nickname'] = $userInfo['nickname'];
	                $score[$k]['headimgurl'] = $userInfo['headimgurl'];
	                $score[$k]['num'] = $num;
	                $num++;
	            }
	        }
	        $arr = array(
	            'data' => $score
	        );
	    }
	    return $arr;
	}
	
	/**
	 * 更新分享的游戏次数
	 */
	public function shareUpdate()
	{
	    $index = Model('index');
	    $res = array('error' => 1, 'content' => '');
	    $config = $index->getGameConfig();
	    $result = $index->updateGameShare($config['share_count'], $config['max_share'], session('wxid'), session('openid'));
	    if($result)
	    {
	        $res['error'] = 0;
	    }
        $recode = $index->getUserJoinInfo(session('wxid'), session('openid'));
        $canplay = $this->playStatus($config, $recode);
        session('canplayStatus', $canplay['status']);
        session('canplayType', $canplay['type']);
        $this->showMsg($canplay);
	}
	
	/**
	 * 提交分数
	 */
	public function sendScore()
	{
	    $index = Model('index');
	    $config = $index->getGameConfig();
	    $res = array('error' => 1, 'content' => '系统繁忙', 'url' => '');
	    $nowTime = yf_time();
	    $lastTime = $config['last_date'];
	    if($nowTime > $lastTime)
	    {
	        $this->showMsg($res);
	    }
	    $info['wxid'] = yf_empty(intval($_POST['wxid']), 'wxid参数错误');
	    $info['openid'] = yf_empty($_POST['openid'], 'openid参数错误');
	    $sign = yf_empty($_POST['sign'], 'sign参数错误');
	    $info['jid'] = yf_empty(intval($_POST['jid']), 'id参数错误');
	    $info['shareWxid'] = yf_empty(intval($_POST['shareWxid']), 0, true);
	    $info['shareOpenid'] = yf_empty($_POST['shareOpenid'], 0, true);
	    $info['score'] = yf_empty(intval($_POST['score']), 0, true);
	    if($info['score'] > 2000)
	    {
	        $res['content'] = '非法分数大于2000';
	        $this->showMsg($res);
	    }
	    $info['gameIp'] = hy_getIP();
	    $info['created'] = yf_time();
	    $gameType = yf_empty($_POST['gameType'], 'gameType参数错误');
	    $tempSign = $this->setSign(array('wxid' => $info['wxid'], 'openid' => $info['openid'], 'recode' => $info['jid']));
	    if($tempSign !== $sign)
	    {
	        $res['content'] = 'sign匹配不正确';
	        $this->showMsg($res);
	    }
	    $isExistRecode = $index->isExistRecode(array('jid' => $info['jid'], 'wxid' => $info['wxid'], 'openid' => $info['openid']));
	    if($isExistRecode)
	    {
	        $info['shareWxid'] = 0;
	        $info['shareOpenid'] = 0;
	    }
	    $info['status'] = 1;
	    $user_count = $index->getLimitRecode($info['wxid'], $info['openid'], $config['limit_time']);
	    if($user_count > $config['limit_count'])
	    {
	        $info['statue'] = 0;
	    }
	    $result = $index->insertRecode($info);
	    
	    if($result)
	    {
	        if($gameType == 'gameCount')
	        {
	            $gameArr = array(
	                'count' => 'gameCount',
	                'score' => 'gameScore'
	            );
	        }
	        if($gameType == 'shareCount')
	        {
	            $gameArr = array(
	                'count' => 'shareCount',
	                'score' => 'shareScore'
	            );
	        }
	        if(!$isExistRecode && $info['shareWxid'] && $info['shareOpenid'])
	        {
	            if($config['add_type'])
	            {
    	            $index->updateJoinScore(
    	                array(
    	                    'addScore' => $info['score'], 
    	                    'allScore' => $info['score']
    	                ), 
    	                array(
    	                    'wxid' => $info['shareWxid'], 
    	                    'openid' => $info['shareOpenid']
    	                )
                    );
	            }
	            if($config['is_share'])
	            {
	                if($config['share_type'] == 2)
	                {
	                    $index->updateGameShare($config['share_count'], $config['max_share'], $info['shareWxid'], $info['shareOpenid']);
	                }
	            }
	        }
	        if($config['limit_status'])
	        {
    	        if($user_count > $config['limit_count'])
    	        {
    	            $index->updateJoinScore(
    	                array(
    	                    'noScore' => $info['score'], 
    	                    'allCount' => 1,
    	                    $gameArr['count'] => 1,
    	                    'lastTime' => yf_time(),
    	                    'lastIp' => hy_getIP()
     	                ), 
    	                array(
    	                    'wxid' => $info['wxid'], 
    	                    'openid' => $info['openid']
    	                )
	                );
    	        }
    	        else 
    	        {
    	            $index->updateJoinScore(
    	                array(
                            'allScore' => $info['score'], 
    	                    'allCount' => 1,
	                        $gameArr['count'] => 1,
    	                    $gameArr['score'] => $info['score'],
    	                    'lastTime' => yf_time(),
    	                    'lastIp' => hy_getIP()
    	                ), 
    	                array(
    	                    'wxid' => $info['wxid'], 
    	                    'openid' => $info['openid']
    	                )
	                );
    	        } 
	        }
	        else 
	        {
	            $index->updateJoinScore(
	                array(
	                    'allScore' => $info['score'],
	                    'allCount' => 1,
	                    $gameArr['count'] => 1,
	                    $gameArr['score'] => $info['score'],
	                    'lastTime' => yf_time(),
	                    'lastIp' => hy_getIP()
	                ),
	                array(
	                    'wxid' => $info['wxid'],
	                    'openid' => $info['openid']
	                )
	            );
	        }
	        $res = array('error' => 0, 'content' => '提交成功', 'url' => '');
	    }
	    $this->showMsg($res);
	}
	
	/**
	 * 开启前判断
	 */
	public function checkAgain()
	{
	    $wxid = yf_empty(intval($_GET['wxid']), '参数错误');
	    $openid = yf_empty($_GET['openid'], '参数错误');
	    $index = Model('index');
	    $config = $index->getGameConfig();
	    $recode = $index->getUserJoinInfo($wxid, $openid);
	    $canplay = $this->playStatus($config, $recode);
	    $this->showMsg($canplay);
	}
	
	/**
	 * 设置签名参数
	 * @param $arr
	 * @return string
	 */
	public function setSign($arr)
	{
	    $str = "";
	    if(is_array($arr))
	    {
	        $temp = array();
	        foreach($arr as $k => $v)
	        {
	            $temp[] = $k."=".$v;
	        }
	        $str = sha1(strtoupper(implode("&", $temp)));
	    }
	    return $str;
	}
	
	/**
	 * 设置session
	 */
	public function setSession()
	{
	    session('wxid', 1);
	    session('openid', 'oyv3Ysnu3mtnrJUfKFWNiXUM1jLk');
	    session('nickname', 'GZhuo文');
	    $this->index();
	}
	
	/**
	 * 清除session
	 */
	public function clear()
	{
	    session('wxid', null);
	    session('openid', null);
	    session('nickname', null);
	    $this->index();
	}
	
}
